#!/bin/bash

# 中国大陆快速安装脚本 - 使用国内镜像源
# 专为网络环境优化

set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date '+%H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date '+%H:%M:%S')] WARNING:${NC} $1"
}

log "🚀 中国大陆快速安装开始..."

# 1. 跳过 Docker Compose pip 安装，直接使用预编译版本
log "🔧 修复 Docker Compose..."

# 清理失败的安装
pip3 uninstall docker-compose -y 2>/dev/null || true

# 使用国内镜像下载 Docker Compose
log "📦 从国内镜像下载 Docker Compose..."
cd /tmp

# 多个国内镜像源
MIRRORS=(
    "https://mirror.ghproxy.com/https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-Linux-x86_64"
    "https://ghproxy.net/https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-Linux-x86_64"
    "https://hub.gitmirror.com/https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-Linux-x86_64"
)

# 尝试下载
for mirror in "${MIRRORS[@]}"; do
    log "尝试镜像: ${mirror##*/}"
    if curl -L --connect-timeout 10 --max-time 60 "$mirror" -o docker-compose; then
        if [ -s docker-compose ]; then
            log "✅ 下载成功！"
            break
        fi
    fi
    warn "镜像失败，尝试下一个..."
done

# 检查下载结果
if [ ! -s docker-compose ]; then
    warn "所有镜像都失败，尝试直接安装系统版本..."
    dnf install -y docker-compose-plugin 2>/dev/null || {
        log "💡 跳过 Docker Compose，使用 docker build + docker run"
        touch /tmp/skip-compose
    }
else
    # 安装下载的版本
    chmod +x docker-compose
    mv docker-compose /usr/local/bin/docker-compose
    ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
    log "✅ Docker Compose 安装完成"
fi

# 2. 安装 Python 依赖（使用国内源）
log "🐍 安装 Python 依赖..."
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple flask

# 3. 创建项目目录
PROJECT_DIR="/opt/jpom/projects/tetris-game"
log "📁 创建项目目录..."
mkdir -p "${PROJECT_DIR}"
cd "${PROJECT_DIR}"

# 4. 克隆项目（如果还没有）
if [ ! -d ".git" ]; then
    log "📥 克隆项目代码..."
    git clone https://gitee.com/cailei/tetris-game.git .
else
    log "📥 更新项目代码..."
    git pull origin main || git pull origin master
fi

# 5. 设置权限
log "🔐 设置文件权限..."
chmod +x *.sh 2>/dev/null || true
chmod +x webhook-receiver.py 2>/dev/null || true

# 6. 创建修复的 Dockerfile
log "📝 创建修复的 Dockerfile..."
cat > Dockerfile << 'EOF'
# 多阶段构建 - 构建阶段
FROM node:18-alpine AS builder

WORKDIR /app

# 复制 package 文件
COPY package*.json ./

# 安装所有依赖（包括开发依赖）
RUN npm ci

# 复制源代码
COPY . .

# 构建项目
RUN npm run build

# 生产阶段 - 使用 Nginx 提供静态文件服务
FROM nginx:alpine

# 复制自定义 nginx 配置
COPY nginx.conf /etc/nginx/conf.d/default.conf

# 复制构建产物到 nginx 目录
COPY --from=builder /app/dist /usr/share/nginx/html

# 暴露端口
EXPOSE 80

# 启动 nginx
CMD ["nginx", "-g", "daemon off;"]
EOF

# 7. 创建简化的构建脚本（不依赖 docker-compose）
log "📝 创建构建脚本..."
cat > simple-build.sh << 'EOF'
#!/bin/bash
set -e

CONTAINER_NAME="tetris-game"
IMAGE_NAME="tetris-game"
PORT="3000"

echo "🚀 开始构建部署..."

# 拉取最新代码
if [ -d ".git" ]; then
    echo "📥 拉取最新代码..."
    git pull origin main 2>/dev/null || git pull origin master 2>/dev/null || true
fi

# 停止旧容器
if docker ps -q -f name=${CONTAINER_NAME} | grep -q .; then
    echo "🛑 停止旧容器..."
    docker stop ${CONTAINER_NAME}
    docker rm ${CONTAINER_NAME}
fi

# 删除旧镜像
if docker images -q ${IMAGE_NAME} | grep -q .; then
    echo "🗑️ 删除旧镜像..."
    docker rmi ${IMAGE_NAME}
fi

# 构建新镜像
echo "🔨 构建镜像..."
docker build -t ${IMAGE_NAME} .

# 启动容器
echo "🚀 启动容器..."
docker run -d --name ${CONTAINER_NAME} --restart unless-stopped -p ${PORT}:80 ${IMAGE_NAME}

# 检查状态
sleep 3
if docker ps -f name=${CONTAINER_NAME} | grep -q ${CONTAINER_NAME}; then
    echo "✅ 部署成功！访问: http://82.157.51.127:${PORT}"
else
    echo "❌ 部署失败，查看日志: docker logs ${CONTAINER_NAME}"
    exit 1
fi
EOF

chmod +x simple-build.sh

# 7. 启动 Webhook 服务
log "⚙️ 启动 Webhook 服务..."
if [ -f webhook-receiver.service ]; then
    cp webhook-receiver.service /etc/systemd/system/
    systemctl daemon-reload
    systemctl enable webhook-receiver
    systemctl restart webhook-receiver
    sleep 2
fi

# 8. 检查服务状态
log "📊 检查服务状态..."
echo ""
echo "=== 服务状态 ==="
systemctl is-active docker && echo "✅ Docker: 运行中" || echo "❌ Docker: 未运行"
systemctl is-active nginx && echo "✅ Nginx: 运行中" || echo "❌ Nginx: 未运行"
systemctl is-active webhook-receiver && echo "✅ Webhook: 运行中" || echo "❌ Webhook: 未运行"

# 9. 测试连接
log "🧪 测试服务..."
if curl -s http://localhost:9999/health >/dev/null; then
    echo "✅ Webhook 服务正常"
else
    echo "❌ Webhook 服务异常"
fi

# 10. 显示结果
echo ""
log "✅ 快速安装完成！"
echo ""
echo "🌐 访问地址:"
echo "  健康检查: http://82.157.51.127/health"
echo "  Webhook: http://82.157.51.127/webhook/gitee"
echo ""
echo "🔧 测试构建:"
echo "  cd ${PROJECT_DIR}"
echo "  ./simple-build.sh"
echo ""
echo "📝 查看日志:"
echo "  journalctl -u webhook-receiver -f"
echo "  docker logs tetris-game"
echo ""

# 11. 自动测试构建（可选）
read -p "是否立即测试构建？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    log "🧪 开始测试构建..."
    ./simple-build.sh
fi

log "🎉 安装完成！"
